package com.pcj.blog.web;/**
 * @param
 * @author pcj
 * @date 2022/1/5 20:07
 * @return
 */

import com.pcj.blog.po.Blog;
import com.pcj.blog.po.Comment;
import com.pcj.blog.po.User;
import com.pcj.blog.service.BlogService;
import com.pcj.blog.service.CommentService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 *
 * @className CommentController
 * @author pengcj
 * @date 2022/1/5 20:07
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatat;
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";  // blog 页面下的commentList 片段
    }

    @PostMapping("/comments") //评论信息提交
    public String post(Comment comment, HttpSession session){
        User user= (User) session.getAttribute("user");
        Long blogId=comment.getBlog().getId();//前端隐含域里面的  blog.id  拿到当前博客的id
        comment.setBlog(blogService.getBlog(blogId));
        if(user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
//            comment.setNickname(user.getNickname());
        }else{
            comment.setAvatar(avatat);
            comment.setAdminComment(false);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/"+ blogId; //  前端隐含域里面的  blog.id
    }

}
